package com.LeeCode;

import java.util.Stack;

/**
 * 字符串解码
 */
public class Code394 {
    public static void main(String[] args) {
        String s = "3[a2[c]]";
        System.out.println(new Code394().decodeString(s));
    }

    public String decodeString(String s) {
        Stack<Integer> stak_num = new Stack<>();
        Stack<String> stak_res = new Stack<>();
        StringBuilder res = new StringBuilder();

        int num = 0;

        for (Character c : s.toCharArray()) {
            if (c == '[') {
                stak_num.push(num);
                stak_res.push(res.toString());
                num = 0;
                res = new StringBuilder();
            } else if (c == ']') {
                int repeat = stak_num.pop();
                String lastString = stak_res.pop();
                StringBuilder tmp = new StringBuilder();
                for (int i = 0; i < repeat; i++) {
                    tmp.append(res);
                }
                res = new StringBuilder(lastString + tmp);

            } else if ('0' <= c && c <= '9') {
                num = num * 10 + (c - '0');
            } else {
                res.append(c);
            }
        }
        return res.toString();
    }
}
